package org.offsync.nio

import org.offsync.util.DisposableBase
import org.offsync.util.ScheduledExecutor
import org.offsync.util.Time

class DeadlineTimer extends DisposableBase {
  private val executor = new ScheduledExecutor
  private val thread = new Thread(executor)
  
  thread.start()
  
  def executeIn(selector: Selector) = new {
    def at(deadline: Time)(f: => Unit): Unit = {
      executor.execute(deadline) {
        selector.execute(f)
      }
    }
  }
  
  def execute(deadline: Time)(f: => Unit): Unit = executor.execute(deadline) { f }
  
  protected override def onDispose(): Unit = try {
    executor.stop()
  } finally {
    super.onDispose()
  }
}
